#include "stm32l0xx_hal.h"
#include "ADS8866.h"
#include "main.h"
#include "delay.h"
#include "my_spi.h"
#include <stdio.h>

void ads8866_init(struct ads8866_device* dev)
{
	
	//初始化通信接口
	if(dev->com_mode == spi_soft)
	{
		
	}
	//
}

void read_data(struct ads8866_device* dev)
{
	if(dev->com_mode == spi_soft)
	{
		if(dev->interface_mode == three_line)
		{
			//开始转化
			HAL_GPIO_WritePin(dev->io->cs.port,dev->io->cs.pin,GPIO_PIN_RESET);
			HAL_GPIO_WritePin(dev->io->mosi.port,dev->io->mosi.pin,GPIO_PIN_SET);
			HAL_GPIO_WritePin(dev->io->cs.port,dev->io->cs.pin,GPIO_PIN_SET);	
			
			HAL_GPIO_WritePin(dev->io->clk.port,dev->io->clk.pin,GPIO_PIN_RESET);
			HAL_GPIO_WritePin(dev->io->cs.port,dev->io->cs.pin,GPIO_PIN_RESET);
			for(uint8_t i = 0; i < (16); i++)
			{
				HAL_GPIO_WritePin(dev->io->clk.port,dev->io->clk.pin,GPIO_PIN_SET);
				HAL_GPIO_WritePin(dev->io->clk.port,dev->io->clk.pin,GPIO_PIN_RESET);
				if(HAL_GPIO_ReadPin(dev->io->miso.port,dev->io->miso.pin))
				{
					dev->rx_val |= (0x01 << (15-i));
				}
				else
				{
					dev->rx_val &= ~(0x01 << (15-i));
				}
			}
			HAL_GPIO_WritePin(dev->io->cs.port,dev->io->cs.pin,GPIO_PIN_SET);
		}
	}
}



ads8866_io_pin current_io = 
{
	.cs = {ADS8866_CS1_PORT, ADS8866_CS1_PIN},
	.clk = {ADS8866_CLK_PORT, ADS8866_CLK_PIN},
	.mosi = {ADS8866_MOSI1_PORT, ADS8866_MOSI1_PIN},
	.miso = {ADS8866_MISO_PORT, ADS8866_MISO_PIN}
};
ads8866_io_pin voltage_io = 
{
	.cs = {ADS8866_CS2_PORT, ADS8866_CS2_PIN},
	.clk = {ADS8866_CLK_PORT, ADS8866_CLK_PIN},
	.mosi = {ADS8866_MOSI2_PORT, ADS8866_MOSI2_PIN},
	.miso = {ADS8866_MISO_PORT, ADS8866_MISO_PIN}
};

ads8866_dev_t current = 
{
	.device_name = "current",						//设备名称
	.rx_val = 0,						//接收数据的值
	.interface_mode = three_line,//与主机连接模式
	.com_mode = spi_soft,//与主机的通讯模式
	.io = &current_io,
	.init = ads8866_init,				//设备初始化函数
	.read= read_data				//读取数据函数
};
ads8866_dev_t voltage = 
{
	.device_name = "voltage",		//设备名称
	.rx_val = 0,					//接收数据的值
	.interface_mode = three_line,	//与主机连接模式
	.com_mode = spi_soft,			//与主机的通讯模式
	.io = &voltage_io,
	.init = ads8866_init,			//设备初始化函数
	.read= read_data				//读取数据函数
};

void test(void)
{
	while(1)
	{
		printf("---------------------\r\n");
		current.read(&current);
		printf("current:%f\r\n",(current.rx_val*2.5/65535)/2.0);
		printf("---------------------\r\n");
		voltage.read(&voltage);
		printf("voltage:%f\r\n",(voltage.rx_val*2.5/65535)/2.0);

		HAL_Delay(1000);
	}
}


